package net.lab1024.sa.gateway.util;

import org.springframework.http.HttpHeaders;
import org.springframework.web.server.ServerWebExchange;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.List;

/**
 * 流量工具类
 */
public class TrafficUtils {
    private static final String SECRET_SALT = "wps_gateway_salt_2025"; // 防篡改盐值

    // 判断是否为文件上传请求
    public static boolean isMultipartRequest(ServerWebExchange exchange) {
        String contentType = exchange.getRequest().getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
        return contentType != null && contentType.startsWith("multipart/form-data");
    }

    // 生成设备指纹（IP+UA+Accept-Language+盐值）
    public static String generateDeviceFingerprint(ServerWebExchange exchange) {
        String ip = getClientIp(exchange);
        String ua = exchange.getRequest().getHeaders().getFirst(HttpHeaders.USER_AGENT) == null ? "" :
                exchange.getRequest().getHeaders().getFirst(HttpHeaders.USER_AGENT);
        String acceptLang = exchange.getRequest().getHeaders().getFirst(HttpHeaders.ACCEPT_LANGUAGE) == null ? "" :
                exchange.getRequest().getHeaders().getFirst(HttpHeaders.ACCEPT_LANGUAGE);

        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest((ip + ua + acceptLang + SECRET_SALT).getBytes(StandardCharsets.UTF_8));
            return bytesToHex(hash);
        } catch (Exception e) {
            return ip + "_" + ua.hashCode(); // 降级处理
        }
    }

    // 获取客户端真实IP（兼容代理）
    public static String getClientIp(ServerWebExchange exchange) {
        List<String> xForwardedFor = exchange.getRequest().getHeaders().get("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
            return xForwardedFor.get(0).split(",")[0].trim();
        }
        InetSocketAddress remoteAddr = exchange.getRequest().getRemoteAddress();
        return remoteAddr != null ? remoteAddr.getAddress().getHostAddress() : "unknown";
    }

    // 字节数组转十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }

}